import * as bm from "/js/baseModule.js";

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);

        this.hasSelectedProvList = [];
        this.initData();
    }

    afterInstall() {
        let that = this;
        new Vue({
            el: "#area_vue",
            data: {citys: that.nation},
            methods: {
                clickProv: function (prov, e) {
                    // 如果是直辖市
                    if (prov.provCity) {
                        //如果已经勾选
                        if (prov.hasChoosed) {
                            prov.hasChoosed = false;
                            prov.subs[0].hasChoosed = false;
                            prov.containType = 0;

                            //如果没有勾选
                        } else {
                            prov.hasChoosed = true;
                            prov.subs[0].hasChoosed = true;
                            prov.containType = 2;
                        }

                        //正常的省
                    } else {
                        funs.swipeModule('modules/user/ServiceProvArea.js', '100%', 'left', function (mod) {
                            mod.initTpl(prov);
                        })
                        // tomato.getVPresenter<ServiceProvArea>(funs.moduleToUrl('m/user/ServiceProvArea'), (ServiceProvArea) => {
                        //     ServiceProvArea.initTpl(prov);
                        //     funs.loadPage(ServiceProvArea);
                        // })

                    }
                },
                setServiceArea: function () {
                    // 如果选中了全国
                    if ($('.nationwide').attr('choosed') == 'true') {
                        let data = {
                            areas: [],
                            type: 1
                        };
                        api.updateServiceArea(data,{
                            succ: function (pack) {
                                //更新全局数据
                                funs.tip('更新成功', '', 'succ', 2000);
                                globalData.pack.area_id = pack.pack.area_id;
                                //修改业务范围后状态更改
                                globalData.user.has_set_business = true;
                                that.initData();
                                // 调用设置页面的方法，把更新的省份列表传过去
                                that.hasSelectedProvList = ["北京市","天津市","河北省","山西省","内蒙古自治区","辽宁省","吉林省","黑龙江省","上海市","江苏省","浙江省","安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","广西壮族自治区","海南省","重庆市","四川省","贵州省","云南省","西藏自治区","陕西省","甘肃省","青海省","宁夏回族自治区","新疆维吾尔自治区","香港特别行政区","澳门特别行政区"];
                                that.setServiceData();

                                setTimeout(function () {
                                    that._evt_goback()
                                },2000);
                            },
                            fail:function () {
                                funs.tip('提交失败', '请检查网络状态并刷新页面重试', 'fail');
                                setTimeout(function () {
                                    window.location.href = '/index.html';
                                }, 2000);
                            }
                        })

                        //如果不是全国，是选择了部分直辖市
                    } else {
                        let choosedArea = [], choosedAreaName = [];
                        let provs = this.citys;
                        // 取出已经选择了的城市id
                        for (let i = 0, len = provs.length; i < len; i++) {
                            if (provs[i].hasChoosed == true) {
                                choosedArea.push(provs[i].subs[0].adcode);
                                choosedAreaName.push(provs[i].name);
                            }
                        }
                        let data = {
                            areas: choosedArea,
                            type: 4
                        };
                        api.updateServiceArea(data, {
                            succ: function (json) {
                                funs.tip('更新成功', '', 'succ', 2000);
                                //更新全局数据
                                globalData.pack.area_id = json.pack.area_id;
                                //保存选择信息
                                that.nationString = JSON.stringify(that.nation);
                                //修改业务范围后状态更改
                                globalData.user.has_set_business = true;

                                /** ===处理setService需要的省份信息===
                                 * 1，先把原有的data中所有的直辖市（包括港澳）剔除；
                                 * 2，再把现在的选择前置插入到data中
                                 * 3，更新setService需要的数据
                                 */
                                let provCitys = ['北京市', '天津市', '上海市', '重庆市', '香港特别行政区', '澳门特别行政区'];
                                for (let i = 0; i < 6; i++) {
                                    let index = $.inArray(provCitys[i], that.hasSelectedProvList);
                                    if (index > -1) {
                                        that.hasSelectedProvList.splice(index, 1);
                                    }
                                }
                                //把当前选择的直辖市插入原有的省份信息
                                that.hasSelectedProvList.unshift(...choosedAreaName);
                                that.setServiceData();
                                setTimeout(function () {
                                    that._evt_goback()
                                },2000);
                            },
                            fail: function (error) {
                                if (error.status == '41009002') {
                                    funs.tip(error.msg, "请先去设置服务资料，成为工程商", "fail");
                                } else {
                                    funs.tip(error.msg, "", "fail");
                                }
                                setTimeout(that._evt_goback, 2000);
                            }
                        })
                    }
                }
            }
        })

    }

    //处理初始数据
    initData() {
        let that = this;
        let hasChoosedArea = globalData.pack.area_id;
        // 获取全国城市列表，然后把已经选择了的城市做标记
        $.getJSON('/prov_city.json', function (json) {
            that.nation = json;

            for (let i = 0, len = that.nation.length; i < len; i++) {
                let jLen = that.nation[i].subs.length;

                // 如果只有一个城市的省（也就是直辖市），直接处理
                if (jLen == 1) {
                    let city = that.nation[i].subs[0];
                    if ($.inArray(city.adcode, hasChoosedArea) > -1) {
                        that.nation[i].hasChoosed = true;
                        city.hasChoosed = true;
                        that.nation[i].containType = 2;//包含情况，完全包含
                        that.hasSelectedProvList.push(that.nation[i].name);
                    } else {
                        that.nation[i].hasChoosed = false;
                        city.hasChoosed = false;
                        that.nation[i].containType = 0;
                    }
                    that.nation[i].provCity = true;
                } else {
                    //不是直辖市
                    that.nation[i].provCity = false;
                    that.nation[i].hasChoosed = false;

                    //循环当前省份的城市，给已经选择的城市做标记
                    let choosedNum = 0;
                    for (let j = 0; j < jLen; j++) {
                        let city = that.nation[i].subs[j];
                        if ($.inArray(city.adcode, hasChoosedArea) > -1) {
                            city.hasChoosed = true;
                            choosedNum++
                        } else {
                            city.hasChoosed = false;
                        }
                    }
                    /** 判断当前省份已经选择的城市情况，
                     * 完全包含 --> 2
                     * 部分包含 --> 1
                     * 全不包含 --> 0
                     */
                    if (choosedNum == 0) {
                        that.nation[i].containType = 0;
                        that.nation[i].containInfo = "未关注"
                    } else if (choosedNum == jLen) {
                        that.nation[i].containType = 2;
                        that.nation[i].containInfo = "关注全省";
                        that.hasSelectedProvList.push(that.nation[i].name);
                    } else {
                        that.nation[i].containType = 1;
                        that.nation[i].containInfo = "关注部分城市";
                        that.hasSelectedProvList.push(that.nation[i].name);
                    }
                }
            }
            that.nationString = JSON.stringify(that.nation);//保存原有的选择信息
            that.setServiceData();
        });
    }

    //选择全国的按钮点击事件
    _evt_chooseAllNation(obj) {
        let that = this;
        let option = $(obj).find('.pull-right');
        if (option.hasClass('option')) {
            $(obj).attr('choosed', true);
            option.removeClass('option').addClass('icon-checkmark');
            for (let i = 0, len = that.nation.length; i < len; i++) {
                that.nation[i].hasChoosed = true;
                that.nation[i].containType = 2;
                that.nation[i].containInfo = "关注全省"
            }
        } else {
            $(obj).attr('choosed', false);
            option.removeClass('icon-checkmark').addClass('option');
            $.extend(true, that.nation, JSON.parse(that.nationString));
        }
    }

    //单个省份设置之后，更新数据
    setProvData(prov) {
        let that = this;
        let provIndex;
        for (let i = 0, len = this.nation.length; i < len; i++) {
            let provId = prov.adcode;
            if (provId == this.nation[i].adcode) {
                this.nation[i].containType = prov.containType;
                this.nation[i].containInfo = prov.containInfo;
                this.nation[i].subs.length = 0;
                this.nation[i].subs.push(...prov.subs);
                provIndex = i;
            }
        }
        // 更改已选择的省份列表，增删更改 （用于setService模块的关注省份显示）
        let index = $.inArray(prov.name, this.hasSelectedProvList);
        // 如果现在是不再关注该省分
        if (prov.containType == 0) {
            //如果之前有，则删除；之前没有就不用操作
            if (index > -1) {
                this.hasSelectedProvList.splice(index, 1);
            }

            // 如果现在是关注该省分
        } else if (prov.containType == 1 || prov.containType == 2) {
            //如果之前没有，则新增这个省份；之前有就不用操作
            if (index == -1) {
                this.hasSelectedProvList.splice(provIndex, 0, prov.name);
            }
        }
        // 调用设置页面的方法，把更新的省份列表传过去
        that.setServiceData();
        this.nationString = JSON.stringify(this.nation);//保存原有的选择信息
    }

    // 调用设置页面的方法，把更新的省份列表传过去
    setServiceData() {
        let that = this;
        if (that.hasSelectedProvList && that.hasSelectedProvList.length != 0) {
            funs.getModuleFuns('modules/user/SetService.js', function (mod) {
                mod.setProvString(that.hasSelectedProvList);
            });
        }
    }

    //对其他模块提供已关注省份的数据
    getSelectedProv() {
        return this.hasSelectedProvList;
    }
}